package top.monddia.netty.server.server.handler;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import top.monddia.netty.common.model.dto.MessageDto;
import top.monddia.netty.common.model.enums.MessageTypeEnums;

/**
 * Netty服务端消息处理器
 *
 * @author ZYP
 */
public class MessageHandler extends ChannelInboundHandlerAdapter {

    protected Logger logger = LoggerFactory.getLogger(getClass());

    @Override
    public void channelRead(ChannelHandlerContext channelHandlerContext, Object msg) throws Exception {
        logger.info("Receive message: {}", msg.toString());
        // 对象类型正确则处理
        if (msg instanceof MessageDto) {
            MessageDto messageDto = (MessageDto) msg;
            // 判断消息类型
            if (messageDto.getMsgType() == MessageTypeEnums.PING.getValue()) {
                // 发送心跳响应
                sendPong(channelHandlerContext, messageDto);
            }
        }
        super.channelRead(channelHandlerContext, msg);
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext channelHandlerContext, Throwable throwable) {
        channelHandlerContext.close();
    }

    /**
     * 发送心跳响应
     *
     * @param channelHandlerContext
     * @param req
     */
    private void sendPong(ChannelHandlerContext channelHandlerContext, MessageDto req) {
        // 封装消息体
        MessageDto messageDto = new MessageDto();
        messageDto.setVersion(req.getVersion());
        messageDto.setMsgType(MessageTypeEnums.PONG.getValue());
        messageDto.setSeq(req.getSeq());
        messageDto.setBody(new byte[0]);
        // 发送消息
        channelHandlerContext.writeAndFlush(messageDto);
    }
}
